import React, {Component} from 'react';
import {Button, Form, Input, Upload, Icon, message} from "antd";
import {axiosPostFunction, baseUrl} from "../MyConfig/AppConfig";

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

class NewImgComponentForm extends Component {

    state = {
        img_component_id: -1,
        img_url: null,
        loading: false,
    }

    // 点击【提交】按钮之后的函数
    onClickSubmit = (event) => {
        event.preventDefault();
        let form_obj = this.props.form;
        form_obj.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log("表单收到数据：", values);
                axiosPostFunction(
                    "/img_component/new",
                    {
                        ...values,
                        img_url: this.state.img_url,
                        img_component_id: this.state.img_component_id,
                        author_id: parseInt(localStorage.getItem("userInfo:id"),
                            10)
                    },
                    (received_data)=>{
                        let { img_component_id } = received_data;
                        if (img_component_id && img_component_id > 0){
                            message.success("添加成功");
                            setTimeout(()=>{
                                // 重置表单
                                this.props.form.resetFields();
                                this.setState({ img_url: null })
                            }, 800)
                        }else {
                            message.error("添加失败")
                        }
                    },
                    ()=>{
                        message.error("上传失败")
                    })
            }
        });
    }

    // 文件上传前的验证操作
    beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('只能上传 JPG/PNG 文件');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图像大小应该小于 2MB');
        }
        // return isJpgOrPng && isLt2M;
        return false;
    }

    // 处理文件上传过程中的状态变化
    handleChange = info => {
        console.log(info);
        getBase64( info.file, (imageUrl) => {
            console.log("imageUrl", imageUrl)
            this.setState({
                img_url: imageUrl,
                loading: false,
            })
        });
        // if (info.file.status === 'uploading') {
        //     this.setState({ loading: true });
        //     getBase64( info.file.originFileObj, (imageUrl) => {
        //         console.log("imageUrl", imageUrl)
        //         this.setState({
        //             img_url: imageUrl,
        //             loading: false,
        //         })
        //     });
        //     return;
        // }
        // if (info.file.status === 'done') {
        //     // Get this url from response in real world.
        //     getBase64( info.file.originFileObj, (imageUrl) => {
        //         console.log("imageUrl", imageUrl)
        //         this.setState({
        //             img_url: imageUrl,
        //             loading: false,
        //         })
        //     });
        // }
    };

    // 渲染函数
    render() {
        let { img_url } = this.state;
        const { getFieldDecorator } = this.props.form;
        return <Form onSubmit={this.onClickSubmit}>
            <Form.Item>
                {getFieldDecorator('group_name', {
                    rules: [
                        { required: true, message: '请输入组名（Group Name）！',},
                    ],
                })(<Input placeholder="请输入组名（Group Name）"/>)}
            </Form.Item>
            <Form.Item>
                {getFieldDecorator('title', {
                    rules: [
                        { required: true, message: '请输入英文组件名（Title）！',},
                    ],
                })(<Input placeholder="请输入英文组件名（Title）"/>)}
            </Form.Item>
            <Form.Item>
                {getFieldDecorator('text_str', {
                    rules: [
                        { required: true, message: '请输入文本标签（Text Str）！',},
                    ],
                })(<Input placeholder="请输入文本标签（Text Str）"/>)}
            </Form.Item>
            <Upload
                name="img_component"
                listType="picture-card"
                className="img-uploader"
                showUploadList={false}
                action={baseUrl + "/img_component/file"}
                beforeUpload={this.beforeUpload}
                onChange={this.handleChange}
            >
                {img_url!==null ? <img src={img_url} style={{ width: "100%" }}/> : <div>
                    <Icon type="plus" />
                    <div className="ant-upload-text">点击上传</div>
                </div>}
            </Upload>
            <Form.Item>
                <Button htmlType="submit">提交</Button>
            </Form.Item>
        </Form>
    }
}

export default Form.create()(NewImgComponentForm);
